import {
  Injectable,
  NotFoundException,
  ForbiddenException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SendMessageDto } from './dto/send-message.dto';
import { GetMessagesDto } from './dto/get-messages.dto';
import * as MarkdownIt from 'markdown-it';

@Injectable()
export class ChatService {
  private md = new MarkdownIt();

  constructor(private prisma: PrismaService) {}

  async sendMessage(
    chatRoomId: number,
    senderId: number,
    sendMessageDto: SendMessageDto,
  ) {
    const { content, type = 'text', replyToId, fileData } = sendMessageDto;

    // 检查用户是否在聊天室中
    const member = await this.prisma.chatRoomUser.findUnique({
      where: {
        userId_chatRoomId: {
          userId: senderId,
          chatRoomId,
        },
      },
    });

    if (!member) {
      throw new ForbiddenException('您不在此聊天室中');
    }

    // 如果是回复消息，检查原消息是否存在
    if (replyToId) {
      const replyToMessage = await this.prisma.message.findFirst({
        where: {
          id: replyToId,
          chatRoomId,
        },
      });

      if (!replyToMessage) {
        throw new NotFoundException('回复的消息不存在');
      }
    }

    // 处理markdown内容
    let processedContent = content;
    if (type === 'markdown') {
      processedContent = this.md.render(content);
    }

    // 如果是文件消息，处理文件信息
    let filePath = null;
    let fileName = null;
    let fileSize = null;
    let fileType = null;

    if (type === 'file' && fileData) {
      filePath = fileData.fileUrl;
      fileName = fileData.fileName;
      fileSize = fileData.fileSize;
      fileType = fileData.fileType;
    }

    // 创建消息
    const message = await this.prisma.message.create({
      data: {
        content: processedContent,
        type,
        senderId,
        chatRoomId,
        replyToId,
        filePath,
        fileName,
        fileSize,
        fileType,
      },
      include: {
        sender: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
        replyTo: {
          include: {
            sender: {
              select: {
                id: true,
                username: true,
              },
            },
          },
        },
      },
    });

    return message;
  }

  async getMessages(
    chatRoomId: number,
    userId: number,
    getMessagesDto: GetMessagesDto,
  ) {
    const { page = 1, limit = 50 } = getMessagesDto;
    const skip = (page - 1) * limit;

    // 检查用户是否有权限访问聊天室
    const member = await this.prisma.chatRoomUser.findUnique({
      where: {
        userId_chatRoomId: {
          userId,
          chatRoomId,
        },
      },
    });

    if (!member) {
      const chatRoom = await this.prisma.chatRoom.findUnique({
        where: { id: chatRoomId },
      });

      if (!chatRoom || !chatRoom.isPublic) {
        throw new ForbiddenException('您没有权限访问此聊天室');
      }
    }

    const [messages, total] = await Promise.all([
      this.prisma.message.findMany({
        where: { chatRoomId },
        skip,
        take: limit,
        include: {
          sender: {
            select: {
              id: true,
              username: true,
              avatar: true,
            },
          },
          replyTo: {
            include: {
              sender: {
                select: {
                  id: true,
                  username: true,
                },
              },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.message.count({
        where: { chatRoomId },
      }),
    ]);

    return {
      messages: messages.reverse(), // 返回时按时间正序
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async editMessage(messageId: number, userId: number, content: string) {
    const message = await this.prisma.message.findUnique({
      where: { id: messageId },
      include: {
        sender: true,
      },
    });

    if (!message) {
      throw new NotFoundException('消息不存在');
    }

    if (message.senderId !== userId) {
      throw new ForbiddenException('您只能编辑自己的消息');
    }

    // 检查消息是否超过编辑时间限制（例如5分钟）
    const editTimeLimit = 5 * 60 * 1000; // 5分钟
    if (Date.now() - message.createdAt.getTime() > editTimeLimit) {
      throw new ForbiddenException('消息发送超过5分钟，无法编辑');
    }

    const updatedMessage = await this.prisma.message.update({
      where: { id: messageId },
      data: {
        content,
        isEdited: true,
        updatedAt: new Date(),
      },
      include: {
        sender: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
        replyTo: {
          include: {
            sender: {
              select: {
                id: true,
                username: true,
              },
            },
          },
        },
      },
    });

    return updatedMessage;
  }

  async deleteMessage(messageId: number, userId: number) {
    const message = await this.prisma.message.findUnique({
      where: { id: messageId },
      include: {
        sender: true,
        chatRoom: {
          include: {
            users: {
              where: { userId },
            },
          },
        },
      },
    });

    if (!message) {
      throw new NotFoundException('消息不存在');
    }

    // 检查权限：发送者或管理员/房主可以删除消息
    const isOwner = message.chatRoom.users[0]?.role === 'owner';
    const isAdmin = message.chatRoom.users[0]?.role === 'admin';
    const isSender = message.senderId === userId;

    if (!isSender && !isOwner && !isAdmin) {
      throw new ForbiddenException('您没有权限删除此消息');
    }

    await this.prisma.message.delete({
      where: { id: messageId },
    });

    return { message: '消息已删除' };
  }
}
